/**
 * 
 */
package net.sahv.bdyz.service;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import net.sahv.bdyz.mapper.AddressMapper;
import net.sahv.bdyz.mapper.FabricMapper;
import net.sahv.bdyz.mapper.OrdersListMapper;
import net.sahv.bdyz.mapper.OrdersMapper;
import net.sahv.bdyz.mapper.PatternMapper;
import net.sahv.bdyz.mapper.PatternPrintMapper;
import net.sahv.bdyz.mapper.ShoppingCartMapper;
import net.sahv.bdyz.model.Address;
import net.sahv.bdyz.model.Fabric;
import net.sahv.bdyz.model.Member;
import net.sahv.bdyz.model.Orders;
import net.sahv.bdyz.model.OrdersList;
import net.sahv.bdyz.model.Pattern;
import net.sahv.bdyz.model.PatternPrint;
import net.sahv.bdyz.model.ShoppingCart;
import net.sahv.bdyz.util.AlipayConfig;
import net.sahv.bdyz.util.AlipaySubmit;
import net.sahv.bdyz.util.Jiage;
import net.sahv.bdyz.util.MyException;
import net.sahv.bdyz.util.PageInfo;


@Service
public class OrdersService {

	@Autowired
	private MemberService memberService;
	@Autowired
	private OrdersMapper ordersMapper;
	@Autowired
	private AddressMapper addressMapper;
	@Autowired
	private OrdersListMapper ordersListMapper;
	@Autowired
	private PatternMapper patternMapper;
	@Autowired
	private PatternPrintMapper patternPrintMapper;
	@Autowired
	private FabricMapper fabricMapper;
	@Autowired
	private ShoppingCartMapper shoppingCartMapper;

	public int deleteByPrimaryKey(Integer oId) {
		return ordersMapper.deleteByPrimaryKey(oId);
	}

	public int insert(Orders record) {
		return ordersMapper.insert(record);
	}

	public Orders selectByPrimaryKey(Integer oId) {
		return ordersMapper.selectByPrimaryKey(oId);
	}

	public List<Orders> selectAll() {
		return ordersMapper.selectAll();
	}

	public int updateByPrimaryKey(Orders record) {
		return ordersMapper.updateByPrimaryKey(record);
	}
	@Transactional
	public int zhijiegoumai(HttpServletRequest request, String status, String pId, String ppId, String fId, String size,
			String addId, String instate,String taitou,String colorImg) {
		Address address = addressMapper.selectByPrimaryKey(Integer.valueOf(addId)); // 查看收货地址
		Member member = memberService.getCurrent();//获取当前登录人信息
		Orders orders = new Orders();
		orders.setoNo(System.currentTimeMillis() + "");
		orders.setoState(0);
		orders.setoName(address.getaName());
		orders.setoPhone(address.getaPhone());
		orders.setoAddress(address.getaAddress());
		orders.setoAddressInfo(address.getaAddressInfo());
		orders.setoPatternImg(address.getaCode());//当邮编使用
		orders.setoInvoiceState(Integer.valueOf(instate));
		orders.setoPatternNo(taitou);
		orders.setmId(member.getmId());
		orders.setoCreatTime(new Date());
		ordersMapper.insert(orders);

		OrdersList orderslist = new OrdersList();
		if (status.equals("0")) {//印花总价 50米以下2倍     51~300米1.5倍    301~1000米1.2倍   1000米以上1倍
			PatternPrint patternPrint = patternPrintMapper.selectByPrimaryKey(Integer.valueOf(ppId));// 印花工艺
			Pattern pattern = patternMapper.selectByPrimaryKey(Integer.valueOf(pId));// 花型
			orderslist.setOlOid(orders.getoId());
			orderslist.setOlPatternNo(pattern.getpNo());
			orderslist.setOlPatternImg(pattern.getpImg());
			orderslist.setOlPatternSize(pattern.getChicun());
			orderslist.setOlPatternPrice(patternPrint.getPpPrice());
			orderslist.setOlFabricSize(Integer.valueOf(size));
			orderslist.setOlType(0);
			orderslist.setMessage1(patternPrint.getPpId()+"");
			orderslist.setOlCreateTime(new Date());
			orderslist.setOlIsDelete(0);
			Integer sizee = Integer.valueOf(size);
			BigDecimal heji = Jiage.yinhua(sizee);
			orderslist.setMessage2(orderslist.getOlPatternPrice().multiply(heji)+"");
			ordersListMapper.insert(orderslist);
			orders.setoTotalPrice(orderslist.getOlPatternPrice().multiply(heji));
		
			ordersMapper.updateByPrimaryKey(orders);

		}
		if (status.equals("1")) {
			//这是要买断花型啊，必须来个记号
			orders.setoType(1);
			Pattern pattern = patternMapper.selectByPrimaryKey(Integer.valueOf(pId));// 花型
			orderslist.setOlOid(orders.getoId());
			orderslist.setOlPatternNo(pattern.getpNo());
			orderslist.setOlPatternImg(pattern.getpImg());
			orderslist.setOlPatternSize(pattern.getChicun());
			orderslist.setOlPatternPrice(pattern.getpBuyoutPrice());
			orderslist.setOlFabricSize(Integer.valueOf(size));
			orderslist.setOlType(1);
			orderslist.setOlCreateTime(new Date());
			orderslist.setOlIsDelete(0);
			orderslist.setMessage2(pattern.getpBuyoutPrice()+"");
			ordersListMapper.insert(orderslist);
			orders.setoTotalPrice(orderslist.getOlPatternPrice().multiply(new BigDecimal(size)));
			ordersMapper.updateByPrimaryKey(orders);

		}
		if (status.equals("2")) {
			PatternPrint patternPrint = patternPrintMapper.selectByPrimaryKey(Integer.valueOf(ppId));// 印花工艺
			Pattern pattern = patternMapper.selectByPrimaryKey(Integer.valueOf(pId));// 花型
			Fabric fabric = fabricMapper.selectByPrimaryKey(Integer.valueOf(fId)); // 面料
			orderslist.setOlOid(orders.getoId());
			orderslist.setOlPatternNo(pattern.getpNo());
			orderslist.setOlPatternImg(pattern.getpImg());
			orderslist.setOlPatternSize(pattern.getChicun());
			orderslist.setOlType(2);
			orderslist.setMessage1(patternPrint.getPpId()+"");
			orderslist.setOlFabricNo(fabric.getfNo());
			orderslist.setOlFabricImg(fabric.getfImg());
			orderslist.setOlFabricSize(Integer.valueOf(size));
			orderslist.setOlCreateTime(new Date());
			orderslist.setOlPatternPrice(patternPrint.getPpPrice().add(fabric.getfPrice()));
			orderslist.setOlIsDelete(0);
			Integer sizee = Integer.valueOf(size);
			BigDecimal mianliao=new BigDecimal(0); 
			mianliao = fabric.getfPrice().multiply(Jiage.mianliao(sizee));
		
			BigDecimal yinhua=new BigDecimal(0); 
			
			yinhua = patternPrint.getPpPrice().multiply(Jiage.yinhua(sizee));
			orderslist.setMessage2(yinhua.add(mianliao)+"");
			ordersListMapper.insert(orderslist);
		
			orders.setoTotalPrice(yinhua.add(mianliao));
			ordersMapper.updateByPrimaryKey(orders);

		}
		if (status.equals("3")) {// 100米以下1.3倍     101~500米1.15倍    500米以上1倍
			Fabric fabric = fabricMapper.selectByPrimaryKey(Integer.valueOf(fId)); // 面料
			orderslist.setOlOid(orders.getoId());
			orderslist.setOlPatternPrice(fabric.getfPrice());
			orderslist.setOlType(3);
			orderslist.setOlFabricNo(fabric.getfNo());
			orderslist.setOlFabricImg(fabric.getfImg());
			orderslist.setOlFabricSize(Integer.valueOf(size));
			orderslist.setOlCreateTime(new Date());
			orderslist.setOlIsDelete(0);
			orderslist.setMessage3(colorImg);
			Integer sizee = Integer.valueOf(size);
			BigDecimal heji = Jiage.mianliao(sizee);
			orderslist.setMessage2(orderslist.getOlPatternPrice().multiply(heji)+"");
			ordersListMapper.insert(orderslist);
			orders.setoTotalPrice(orderslist.getOlPatternPrice().multiply(heji));
			ordersMapper.updateByPrimaryKey(orders);
		}

		return 1;

	}

	@Transactional
	public int shengchengdingdan(HttpServletRequest request, String[] oId,String addId, String instate, String taitou) throws MyException {
		BigDecimal count = new BigDecimal(0);
		Address address = addressMapper.selectByPrimaryKey(Integer.valueOf(addId)); // 查看收货地址
		Member member = memberService.getCurrent();//获取当前登录人信息
		Orders orders = new Orders();
		orders.setoNo(System.currentTimeMillis() + "");
		orders.setoState(0);
		orders.setoName(address.getaName());
		orders.setoPhone(address.getaPhone());
		orders.setoAddress(address.getaAddress());
		orders.setoPatternImg(address.getaCode());//当邮编使用
		orders.setoAddressInfo(address.getaAddressInfo());
		orders.setoInvoiceState(Integer.valueOf(instate));
		orders.setoPatternNo(taitou);
		orders.setoCreatTime(new Date());
		orders.setmId(member.getmId());
		ordersMapper.insert(orders);
		boolean flag = false;
		for(String oid:oId){
			ShoppingCart shoppingCart = shoppingCartMapper.selectByPrimaryKey(Integer.valueOf(oid));
			Pattern pattern = patternMapper.selectByNo(shoppingCart.getScPatternNo());
			if(pattern!=null&&pattern.getpBuyoutState().equals(1)){
				throw new MyException(pattern.getpId().toString());
			}
			OrdersList orderslist = new OrdersList();
			orderslist.setOlOid(orders.getoId());
			orderslist.setOlPatternNo(shoppingCart.getScPatternNo());
			orderslist.setOlPatternImg(shoppingCart.getScPatternImg());
			orderslist.setOlPatternSize(shoppingCart.getScPatternSize());
			orderslist.setOlPatternPrice(shoppingCart.getScPatternSinglePrice());
			orderslist.setMessage1(shoppingCart.getPpId()+"");
			orderslist.setMessage3(shoppingCart.getFabricColor());
			orderslist.setOlType(shoppingCart.getScType());
			if(shoppingCart.getScType()==1){
				//这是要买断花型啊，必须来个记号	
				flag=true;
			}
			orderslist.setOlFabricNo(shoppingCart.getScFabricNo());
			orderslist.setOlFabricImg(shoppingCart.getScFabricImg());
			orderslist.setOlFabricSize(shoppingCart.getScFabricSize());
			orderslist.setOlCreateTime(new Date());
			orderslist.setOlIsDelete(0);
			orderslist.setMessage2(shoppingCart.getScTotalPrice()+"");
			ordersListMapper.insert(orderslist);
			count = (shoppingCart.getScTotalPrice()).add(count);
			shoppingCartMapper.deleteByPrimaryKey(Integer.valueOf(oid));
		}
		if(flag){
			orders.setoType(1);
		}
		orders.setoTotalPrice(count);
		ordersMapper.updateByPrimaryKey(orders);
		return 1;
	}

	public List<Map<String, Object>> findAll(PageInfo pageInfo, String where, String order) {
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("myCount", pageInfo.getCount());
		param.put("pageSize", pageInfo.getPageSize());
		param.put("page", pageInfo.getPage());
		param.put("where", where);
		param.put("order", order);
		List<Map<String, Object>> m = ordersMapper.findAll(param);
		pageInfo.setCount(Integer.parseInt(param.get("myCount").toString()));
		return m;
	}

	public Orders selectByNo(String oNo) {
		return ordersMapper.selectByNo(oNo);
	}

	public List<Map<String, Object>> getList(Map<String, Object> param) {
		return ordersMapper.getList(param);
	}

	public Integer getTotalCount(String where) {
		return ordersMapper.getTotalCount(where);
	}
	@Transactional(rollbackFor=Exception.class)
	public String pay(String oId) throws Exception {
		Orders orders = ordersMapper.selectByPrimaryKey(Integer.valueOf(oId));
		DateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.MINUTE, 6);  
		orders.setoFabricImg(df.format(calendar.getTime()));
		
	
		ordersMapper.updateByPrimaryKey(orders);
			List<Map<String, Object>> list = ordersListMapper.selectAllByOrdersId(orders.getoId(),"ch");
			for(Map<String, Object> item:list){
				if(item.get("OL_PATTERN_NO")!=null){
					
				Pattern  pattern  = patternMapper.selectByNo(item.get("OL_PATTERN_NO").toString());
				if(pattern.getpBuyoutState()==1){
					throw new Exception();
				}
				if(item.get("OL_TYPE").toString().equals("1")){
					pattern.setpBuyoutState(1);
					patternMapper.updateByPrimaryKey(pattern);
				}
				}
			}

		
		 //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = orders.getoNo();

        //订单名称，必填
        String subject = "步调衣致";

        //付款金额，必填
        String total_fee =orders.getoTotalPrice()+"";

        //商品描述，可空
        String body = "";

		
		
		//////////////////////////////////////////////////////////////////////////////////
		
		//把请求参数打包成数组
		Map<String, String> sParaTemp = new HashMap<String, String>();
		sParaTemp.put("service", AlipayConfig.service);
        sParaTemp.put("partner", AlipayConfig.partner);
        sParaTemp.put("seller_id", AlipayConfig.seller_id);
        sParaTemp.put("_input_charset", AlipayConfig.input_charset);
		sParaTemp.put("payment_type", AlipayConfig.payment_type);
		sParaTemp.put("notify_url", AlipayConfig.notify_url);
		sParaTemp.put("return_url", AlipayConfig.return_url);
		sParaTemp.put("anti_phishing_key", AlipayConfig.anti_phishing_key);
		sParaTemp.put("exter_invoke_ip", AlipayConfig.exter_invoke_ip);
		sParaTemp.put("out_trade_no", out_trade_no);
		sParaTemp.put("subject", subject);
		sParaTemp.put("it_b_pay", "5m");
		sParaTemp.put("total_fee", total_fee);
		sParaTemp.put("body", body);
		//其他业务参数根据在线开发文档，添加参数.文档地址:https://doc.open.alipay.com/doc2/detail.htm?spm=a219a.7629140.0.0.O9yorI&treeId=62&articleId=103740&docType=1
        //如sParaTemp.put("参数名","参数值");
		
		//建立请求
		String sHtmlText = AlipaySubmit.buildRequest(sParaTemp,"get","确认");
		return sHtmlText;
	}
	
	public String vip(Integer mId){
		 //商户订单号，商户网站订单系统中唯一订单号，必填
	
        String out_trade_no = DigestUtils.md5Hex(mId.toString()+System.currentTimeMillis());

        //订单名称，必填
        String subject = "开通vip";

        //付款金额，必填
        String total_fee = "0.01";

        //商品描述，可空
        String body = "";

		
		
		//////////////////////////////////////////////////////////////////////////////////
		
		//把请求参数打包成数组
		Map<String, String> sParaTemp = new HashMap<String, String>();
		sParaTemp.put("service", AlipayConfig.service);
        sParaTemp.put("partner", AlipayConfig.partner);
        sParaTemp.put("seller_id", AlipayConfig.seller_id);
        sParaTemp.put("_input_charset", AlipayConfig.input_charset);
		sParaTemp.put("payment_type", AlipayConfig.payment_type);
		sParaTemp.put("notify_url", AlipayConfig.notify_url);
		sParaTemp.put("return_url", AlipayConfig.return_url);
		sParaTemp.put("anti_phishing_key", AlipayConfig.anti_phishing_key);
		sParaTemp.put("exter_invoke_ip", AlipayConfig.exter_invoke_ip);
		sParaTemp.put("out_trade_no", out_trade_no);
		sParaTemp.put("subject", subject);
		sParaTemp.put("total_fee", total_fee);
		sParaTemp.put("it_b_pay", "5m");
		sParaTemp.put("body", body);
		sParaTemp.put("extra_common_param", mId.toString());
		//其他业务参数根据在线开发文档，添加参数.文档地址:https://doc.open.alipay.com/doc2/detail.htm?spm=a219a.7629140.0.0.O9yorI&treeId=62&articleId=103740&docType=1
        //如sParaTemp.put("参数名","参数值");
		
		//建立请求
		String sHtmlText = AlipaySubmit.buildRequest(sParaTemp,"get","确认");
		return sHtmlText;
	}
	
	public void huigun() {
		List<Orders> list = ordersMapper.getshixiao();
		for(Orders item:list){
			List<Map<String, Object>> ordersList = ordersListMapper.selectAllByOrdersId(item.getoId(),"ch");
			for(Map<String, Object> li:ordersList){
				if(li.get("OL_TYPE").toString().equals("1")){
					Pattern pattern = patternMapper.selectByNo(li.get("OL_PATTERN_NO").toString());
					pattern.setpBuyoutState(0);
					patternMapper.updateByPrimaryKey(pattern);
				}
			}
		}
	}

	public void mianliao(Orders order) {
		
		List<Map<String, Object>> ordersList = ordersListMapper.selectAllByOrdersId(order.getoId(),"ch");
		for(Map<String, Object> li:ordersList){
			if(li.get("OL_FABRIC_NO")!=null){
				fabricMapper.xiaoshou(li.get("OL_FABRIC_NO").toString(),Integer.valueOf(li.get("OL_FABRIC_SIZE").toString()));
			}
		}
	}
	
	

}
